package com.newsee.remote.ecommerce.commerce.jingdong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.bean.JsonResult;
import com.newsee.remote.common.bean.JsonReturn;
import com.newsee.remote.common.database.entity.JdItemPool;
import com.newsee.remote.common.database.entity.ShMaterialclass;
import com.newsee.remote.common.database.mapper.JdItemPoolMapper;
import com.newsee.remote.common.dto.ecommerce.jingdong.JDItemPoolDTO;
import com.newsee.remote.common.dto.ecommerce.jingdong.JDSearchDTO;
import com.newsee.remote.common.enumeration.DeleteFlagEnum;
import com.newsee.remote.common.utils.tools.CcUtils;
import com.newsee.remote.common.vo.ecommerce.*;
import com.newsee.remote.ecommerce.commerce.jingdong.service.IJdItemPoolService;
import com.newsee.remote.ecommerce.commerce.jingdong.service.IJdTokenService;
import com.newsee.remote.ecommerce.service.IShMaterialclassService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.newsee.remote.common.utils.http.HttpClientExecutor.httpPost;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-08-09
 */
@Service
@Slf4j
public class JdItemPoolServiceImpl extends ServiceImpl<JdItemPoolMapper, JdItemPool> implements IJdItemPoolService {

    /**
     * 获取所有商品池
     */
    @Value("${jdGetPageNumUrl}")
    private String jdGetPageNumUrl;

    @Value("${jdSearchUrl}")
    private String jdSearchUrl;

    @Value("${jdSearchPriceUrl}")
    private String jdSearchPriceUrl;

    @Value("${jdImageUrlPre}")
    private String jdImageUrlPre;

    @Value("${jdGetDetailUrl}")
    private String jdGetDetailUrl;

    private final IShMaterialclassService iShMaterialclassService;

    private final IJdTokenService iJdTokenService;

    public JdItemPoolServiceImpl(IJdTokenService iJdTokenService, IShMaterialclassService iShMaterialclassService) {
        this.iJdTokenService = iJdTokenService;
        this.iShMaterialclassService = iShMaterialclassService;
    }

    @Override
    public JsonResult sync() {
        //获取token
        String token = iJdTokenService.getToken();
        //获取所有商品池
        List<JDItemPoolDTO> itemPoolDTOS = getItemPools(token);
        //新增或修改商品池
        if (CollectionUtils.isNotEmpty(itemPoolDTOS)) {
            updateItemPools(itemPoolDTOS);
        } else {
            log.error("京东商品池列表为空！");
        }
        return JsonReturn.succ();
    }

    @Override
    public JsonResult search(JDSearchDTO jdSearchDTO) {
        JDSearchVO jdSearchVO = new JDSearchVO();
        //封装请求参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", iJdTokenService.getToken());

        if (StringUtils.isNotEmpty(jdSearchDTO.getKeyword())) {
            params.put("keyword", jdSearchDTO.getKeyword());
        }

        if (StringUtils.isNotEmpty(jdSearchDTO.getBrands())) {
            params.put("brands", jdSearchDTO.getBrands());
        }

        if (StringUtils.isNotEmpty(jdSearchDTO.getCatId())) {
            //todo 分类关系转换
            QueryWrapper<JdItemPool> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MaterialClassCode",jdSearchDTO.getCatId());
            JdItemPool itemPool = getOne(queryWrapper);
            if (null == itemPool){
                return JsonReturn.succ(jdSearchVO);
            }
            String pageNum = itemPool.getPageNum();
            params.put("catId", pageNum);
           // params.put("catId", jdSearchDTO.getCategoryId());
        }

        if (StringUtils.isNotEmpty(jdSearchDTO.getSortType())) {
            params.put("sortType", jdSearchDTO.getSortType());
        }

        params.put("pageIndex", jdSearchDTO.getPageIndex().toString());
        params.put("pageSize", jdSearchDTO.getPageSize().toString());

        // 执行请求
        String response = httpPost(jdSearchUrl, params);
        //返回对象
        SearchVO searchVO = null;
        try {
            //解析结果
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                jdSearchVO = JSONObject.parseObject(jsonReturn.toJSONString(), JDSearchVO.class);
            }

            //封装返回
            searchVO = handlePrice(jdSearchVO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析京东商品池失败：" + e.getMessage());
        }

        return JsonReturn.succ(searchVO);
    }

    /**
     * 获取京东商品价格
     *
     * @param vo 实体
     */
    private SearchVO handlePrice(JDSearchVO vo) {
        //返回统一的电商返回对象
        SearchVO searchVO = new SearchVO();

        if (vo.isSuccess()) {
            JDSearchVO.ResultBean result = vo.getResult();
            //分页信息
            searchVO.setResultCount(result.getResultCount());
            searchVO.setPageCount(result.getPageCount());
            searchVO.setPageIndex(result.getPageIndex());
            searchVO.setPageSize(result.getPageSize());
            //当前页商品信息
            List<SearchSkuVO> skuVOS = new ArrayList<>();
            searchVO.setSkus(skuVOS);


            List<JDSearchVO.ResultBean.HitResultBean> hitResult = result.getHitResult();
            List<String> skus = CcUtils.collect(hitResult, JDSearchVO.ResultBean.HitResultBean::getWareId);


            if (CollectionUtils.isNotEmpty(skus)) {
                String sku = StringUtils.join(skus.toArray(), ",");
                //查询商品的价格
                JDSearchPriceVO priceVO = searchPrice(sku);
                List<JDSearchPriceVO.ResultBean> prices = priceVO.getResult();
                hitResult.forEach(hit -> {
                    SearchSkuVO detailVo = new SearchSkuVO();
                    //封装图片前缀
                    if (StringUtils.isNotEmpty(hit.getImageUrl())) {
                        detailVo.setImagePath(jdImageUrlPre + hit.getImageUrl());
                    }
                    //封装价格
                    prices.forEach(price -> {
                        if (hit.getWareId().equals(String.valueOf(price.getSkuId()))) {
                            detailVo.setPrice(price.getPrice());
                        }
                    });
                    //封装融创3级分类
                    buildRcClass(detailVo, hit.getCatId());

                    detailVo.setBrand(hit.getBrand());
                    detailVo.setName(hit.getWareName());
                    detailVo.setSku(hit.getWareId());
                    detailVo.setState(hit.getWstate());
                    detailVo.setSupplier("1000005465");
                    skuVOS.add(detailVo);
                });
            }
        }

        return searchVO;
    }

    /**
     * 封装融创的3级分类id
     *
     * @param detailVo 返回
     * @param catId    京东3级分类id
     */
    private void buildRcClass(SearchSkuVO detailVo, String catId) {
        if (StringUtils.isEmpty(catId)) {
            //行政其他分类
            detailVo.setMaterialClassID("XZ0101");
        } else {
            QueryWrapper<JdItemPool> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("Page_Num", catId);
            JdItemPool jdItemPool = getOne(queryWrapper);
            if (null == jdItemPool) {
                detailVo.setMaterialClassID("XZ0101");
            } else {
                detailVo.setMaterialClassID(jdItemPool.getMaterialClassCode());
            }
        }
        String materialClassCode = detailVo.getMaterialClassID();
        QueryWrapper<ShMaterialclass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Code", materialClassCode);
        ShMaterialclass shMaterialclass = iShMaterialclassService.getOne(queryWrapper);
        if (null != shMaterialclass) {
            detailVo.setMaterialClassID(shMaterialclass.getId().toString());
        } else {
            detailVo.setMaterialClassID("XZ0101");
        }

        //转换成id
        if ("XZ0101".equals(detailVo.getMaterialClassID())) {
            QueryWrapper<ShMaterialclass> queryWrapperXZ = new QueryWrapper<>();
            queryWrapperXZ.eq("Code", "XZ0101");
            ShMaterialclass one = iShMaterialclassService.getOne(queryWrapperXZ);
            if (null != one) {
                detailVo.setMaterialClassID(one.getId().toString());
            }
        }
    }

    /**
     * 获取sku详情信息
     *
     * @param sku sku
     */
    private JDSkuDetailVO.ResultBean getSkuDetail(String sku) {
        JDSkuDetailVO.ResultBean bean = new JDSkuDetailVO.ResultBean();
        //封装请求参数
        Map<String, String> params = new HashMap<>(2);
        params.put("token", iJdTokenService.getToken());
        params.put("sku", sku);
        // 执行请求
        String response = httpPost(jdGetDetailUrl, params);
        //返回对象
        JDSkuDetailVO vo;
        try {
            //解析结果
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                vo = JSONObject.parseObject(jsonReturn.toJSONString(), JDSkuDetailVO.class);
                if (vo.isSuccess()) {
                    bean = vo.getResult();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析京东商品详情失败：" + e.getMessage());
        }

        return bean;
    }

    /**
     * 批量获取获取sku详情信息
     *
     * @param skus sku集合
     */
    private List<JDSkuDetailVO.ResultBean> getSkuDetail(List<String> skus) {
        List<JDSkuDetailVO.ResultBean> beans = new ArrayList<>();
        //封装请求参数
        Map<String, String> params = new HashMap<>(2);
        params.put("token", iJdTokenService.getToken());
        for (String sku : skus) {
            params.put("sku", sku);
            // 执行请求
            String response = httpPost(jdGetDetailUrl, params);
            //返回对象
            JDSkuDetailVO vo;
            try {
                //解析结果
                JSONObject jsonReturn = JSON.parseObject(response);
                if (null != jsonReturn) {
                    vo = JSONObject.parseObject(jsonReturn.toJSONString(), JDSkuDetailVO.class);
                    if (vo.isSuccess()) {
                        beans.add(vo.getResult());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("解析京东商品详情失败：" + e.getMessage());
            }
        }

        return beans;
    }


    @Override
    public JDSearchPriceVO searchPrice(String sku) {
        //封装请求参数
        Map<String, String> params = new HashMap<>(3);
        params.put("token", iJdTokenService.getToken());
        params.put("sku", sku);
        params.put("queryExts", "Price");


        // 执行请求
        String response = httpPost(jdSearchPriceUrl, params);
        //返回对象
        JDSearchPriceVO vo = new JDSearchPriceVO();

        try {
            //解析结果
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                vo = JSONObject.parseObject(jsonReturn.toJSONString(), JDSearchPriceVO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析京东商品价格失败：" + e.getMessage());
        }

        return vo;
    }

    @Override
    public JsonResult skuDetail(String skuId) {
        JDSkuDetailVO.ResultBean skuDetail = getSkuDetail(skuId);
        JDSearchPriceVO priceVO = searchPrice(skuId);
        SkuDetailVO skuDetailVO = new SkuDetailVO();
        BeanUtils.copyProperties(skuDetail, skuDetailVO);
        skuDetailVO.setBrand(skuDetail.getBrandName());
        skuDetailVO.setSku(String.valueOf(skuDetail.getSku()));
        skuDetailVO.setSupplier("京东");

        //封装图片前缀
        if (StringUtils.isNotEmpty(skuDetail.getImagePath())) {
            skuDetailVO.setImagePath(jdImageUrlPre + skuDetail.getImagePath());
        }
        //封装价格
        if (priceVO.isSuccess()) {
            skuDetailVO.setPrice(priceVO.getResult().get(0).getPrice());
        }

        return JsonReturn.succ(skuDetailVO);
    }

    /**
     * 新增或修改商品池
     *
     * @param itemPoolDTOS 所有最新的商品池
     */
    private void updateItemPools(List<JDItemPoolDTO> itemPoolDTOS) {
        Map<String, JDItemPoolDTO> dtoMap = CcUtils.toMap(itemPoolDTOS, JDItemPoolDTO::getPage_num);
        LocalDateTime now = LocalDateTime.now();


        List<JdItemPool> list = getList();
        list.forEach(jdItemPool -> {
            JDItemPoolDTO poolDTO = dtoMap.get(jdItemPool.getPageNum());
            if (null == poolDTO) {
                //删除
                jdItemPool.setDeleteFlag(DeleteFlagEnum.IS_DELETE.getCode());
                jdItemPool.setUpdateTime(now);
                updateById(jdItemPool);
            } else {
                //是否修改
                if (!poolDTO.getName().equals(jdItemPool.getName())) {
                    jdItemPool.setUpdateTime(now);
                    jdItemPool.setName(poolDTO.getName());
                    updateById(jdItemPool);
                }
            }
            itemPoolDTOS.remove(poolDTO);
        });

        itemPoolDTOS.forEach(itemPoolDTO -> {
            JdItemPool jdItemPool = new JdItemPool();
            jdItemPool.setName(itemPoolDTO.getName());
            jdItemPool.setPageNum(itemPoolDTO.getPage_num());
            save(jdItemPool);
        });
    }

    private List<JdItemPool> getList() {
        QueryWrapper<JdItemPool> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper);
    }

    /**
     * 获取所有的商品池
     *
     * @param token token
     * @return 商品池s
     */
    private List<JDItemPoolDTO> getItemPools(String token) {
        List<JDItemPoolDTO> result = new ArrayList<>();

        Map<String, String> params = new HashMap<String, String>(1);
        params.put("token", token);
        // 执行请求
        String response = httpPost(jdGetPageNumUrl, params);

        try {
            //解析结果
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                Boolean success = jsonReturn.getBoolean("success");
                if (success) {
                    result = JSONObject.parseArray(jsonReturn.getString("result"), JDItemPoolDTO.class);
                } else {
                    log.error("解析京东商品池失败：" + jsonReturn.toJSONString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析京东商品池失败：" + e.getMessage());
        }

        return result;
    }
}
